<template>
  <div
    v-if="dialogTableVisible1"
    :fullscreen="false"
    :modal="false"
    :show-close="false"
    :width="screenWidth + 20 + 'px'"
    :append-to-body="true"
    style="
      position: absolute;
      left: 6rem;
      margin-top: 42px;
      z-index: 10;
      background-color: white;
    "
    :close-on-click-modal="false"
  >
    <div :style="{ width: screenWidth - 96 + 'px' }">
      <div
        :style="{
          height: '40px',
          borderBottom: '1px solid #ccc',
          width: '100%',
        }"
      >
        <div style="position: absolute; right: 15px">
          <el-button @click="flushed" type="primary"> 刷新</el-button>
          <!-- <el-button v-if="Permission" @click="upButton" type="primary">
        修改业务员</el-button
      > -->
          <el-button @click="addRow" type="primary">增行</el-button>
          <el-button @click="addSign" type="success" v-if="!showInsertButton"
            >签批</el-button
          >
          <el-button @click="delSign" type="warning" v-if="!showInsertButton"
            >弃签</el-button
          >
          <el-button
            type="primary"
            @click="getAllData(ruleFormRef)"
            v-if="showInsertButton"
            >保存</el-button
          >
          <!-- <el-button
            type="primary"
            @click="updateMaterialsFixed(ruleFormRef)"
            v-if="!showInsertButton"
            >修改</el-button
          > -->
          <el-button @click="deleteSelectedRows" type="danger">删除</el-button>
          <el-button @click="OFFdialogTableVisible" type="danger">关闭</el-button>
        </div>
      </div>
    </div>

    <div
      ref="titleDiv"
      :style="{
        backgroundColor: 'rgba(247, 247, 247, 0.903)',
        height: 100 + 'px',
        width: screenWidth - 96 + 'px',
      }"
    >
      <el-form :model="formMainTable" :inline="true">
        <el-form :model="formMainTable" :inline="true">
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 80px; padding-right: 5px"
              ><span style="color: red; font-weight: 700">*</span> 工单编码</label
            >
            <el-input
              style="width: 120px"
              v-model="formMainTable.workOrderCode"
              :readonly="true"
              @click="openWorkOrderCode()"
              :disabled="!showInsertButton"
            />
          </el-form-item>

          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 80px; padding-right: 5px"
              ><span style="color: red">*</span>计划类型</label
            >
            <el-input
              style="width: 120px"
              v-model="formMainTable.planType"
              :readonly="true"
              disabled
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 80px; padding-right: 5px"
              ><span style="color: red">*</span>工单类型</label
            >

            <el-input
              style="width: 120px"
              v-model="formMainTable.workOrderType"
              :readonly="true"
              disabled
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 80px; padding-right: 5px"
              ><span style="color: red">*</span>加工方式</label
            >

            <el-input
              style="width: 120px"
              v-model="formMainTable.processingMethod"
              :readonly="true"
              disabled
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 80px; padding-right: 5px"
              ><span style="color: red">*</span>计划日期</label
            >

            <el-input
              style="width: 120px"
              v-model="formMainTable.djTime"
              :readonly="true"
              disabled
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 80px; padding-right: 5px"
              ><span style="color: red">*</span>计划人员</label
            >
            <el-input
              style="width: 120px"
              v-model="formMainTable.employee"
              :readonly="true"
              disabled
            />
          </el-form-item>
          <el-form-item class="labs" style="margin-right: 0">
            <label class="lab" style="width: 80px; padding-right: 5px"
              ><span style="color: red">*</span>计划部门</label
            >
            <el-input
              style="width: 120px"
              v-model="formMainTable.department"
              :readonly="true"
              disabled
            />
          </el-form-item>
          <el-row>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">磨削标准</label>

              <el-input
                style="width: 120px"
                v-model="formMainTable.grindingStandardMid"
                :readonly="true"
                disabled
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">标准名称</label>

              <el-input
                style="width: 120px"
                v-model="formMainTable.grindingStandardName"
                :readonly="true"
                disabled
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">零件名称</label>

              <el-input
                style="width: 120px"
                v-model="formMainTable.name"
                :readonly="true"
                disabled
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">型号</label>

              <el-input
                style="width: 120px"
                v-model="formMainTable.model"
                :readonly="true"
                disabled
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">单位</label>

              <el-input
                style="width: 120px"
                v-model="formMainTable.measurementUnit"
                :readonly="true"
                disabled
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">单件数量</label>

              <el-input
                style="width: 120px"
                v-model="formMainTable.singlequantity"
                :readonly="true"
                disabled
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">组数量</label>

              <el-input
                style="width: 120px"
                v-model="formMainTable.groupquantity"
                :readonly="true"
                disabled
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">目标设备</label>

              <el-input
                style="width: 120px"
                v-model="formMainTable.equipment"
                :readonly="true"
                disabled
              />
            </el-form-item>

            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">设备编码</label>

              <el-input
                style="width: 120px"
                v-model="formMainTable.equipmentId"
                :readonly="true"
                disabled
              />
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">加工日期</label>

              <el-date-picker
                v-model="formMainTable.processingDay"
                type="date"
                placeholder="选择日期"
                style="width: 120px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px">加工班次</label>
              <el-select
                v-model="formMainTable.processingShift"
                size="medium"
                style="width: 120px"
              >
                <el-option label="早班" value="1"></el-option>
                <el-option label="中班" value="2"></el-option>
                <el-option label="晚班" value="3"></el-option>
                <el-option label="白班" value="3"></el-option>
                <el-option label="夜班" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px"
                ><span style="color: red">*</span>加工班组</label
              >
              <el-input
                :readonly="true"
                style="width: 120px"
                v-model="formMainTable.processingWorkTeam"
                @click="openWorkOrderCode2()"
                placeholder="请点击选择"
              />
              <!-- <el-input
                style="width: 120px"
                v-model="formMainTable.processingWorkTeam"
                :readonly="true"
              /> -->
            </el-form-item>
            <el-form-item class="labs" style="margin-right: 0">
              <label class="lab" style="width: 80px; padding-right: 5px"
                ><span style="color: red">*</span>加工人员</label
              >
              <el-input
                :readonly="true"
                style="width: 120px"
                v-model="formMainTable.processingWorker"
                placeholder=""
              />
            </el-form-item>
          </el-row>
        </el-form>
      </el-form>
    </div>

    <el-table
      ref="multipleTableRef"
      :data="tableData1"
      stripe
      border
      :row-style="{ height: '20px' }"
      :height="childTableHeight + 'px'"
      style="width: 100%"
      :max-height="childTableHeight + 'px'"
      :cell-style="cellStyle1"
      @selection-change="handleSelectionChange1"
      :header-cell-style="headerCellStyle1"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="50" align="center">
        <template #default="{ $index }">
          <span>{{ $index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单件唯一码" width="100" align="center">
        <template #default="{ row, $index }">
          <div style="line-height: 25px; cursor: pointer">
            {{ row.uniqueCode }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="材质" width="80" align="center">
        <template #default="{ row, $index }">
          <span>{{ row.material }}</span>
        </template>
      </el-table-column>
      <el-table-column label="规格" width="80" align="center">
        <template #default="{ row, $index }">
          <span>{{ row.specification }}</span>
        </template>
      </el-table-column>
      <el-table-column label="型号" width="80" align="center">
        <template #default="{ row, $index }">
          <span>{{ row.model }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本次磨削量" width="80" align="center">
        <template #default="{ row, $index }">
          <el-input
            v-model="row.bcGrindingCapacity"
            :style="{ height: '25px' }"
            @blur="handleInput('bcGrindingCapacity', $index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="本次粗糙度" width="80" align="center">
        <template #default="{ row, $index }">
          <el-input
            v-model="row.bcroughnessStandard"
            :style="{ height: '25px' }"
            @blur="handleInput1('bcroughnessStandard', $index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="累计磨削次数" width="100" align="center">
        <template #default="{ row, $index }">
          <span>{{ row.ljgrindingTimes }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余磨削量" width="80" align="center">
        <template #default="{ row, $index }">
          <span>{{ row.residualGrindingCapacity }}</span>
        </template>
      </el-table-column>

      <el-table-column label="磨削总量" width="80" align="center">
        <template #default="{ row, $index }">
          <span>{{ row.totalGrindingAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="粗糙度" width="240" align="center">
        <el-table-column label="标准" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
            </span>
          </template>
          <template #default="{ row, $index }">
            <span>{{ row.roughnessStandard }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下限" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
            </span>
          </template>
          <template #default="{ row, $index }">
            <span>{{ row.roughnessToleranceLower }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上限" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
            </span>
          </template>
          <template #default="{ row, $index }">
            <span>{{ row.roughnessToleranceUpper }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="单次磨削量" width="240" align="center">
        <el-table-column label="单次标准" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
            </span>
          </template>
          <template #default="{ row, $index }">
            <span>{{ row.grindStandard }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下限" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
            </span>
          </template>
          <template #default="{ row, $index }">
            <span>{{ row.grindToleranceLower }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上限" width="100" align="center">
          <template #header="{ column }">
            <span>
              {{ column.label }}
            </span>
          </template>
          <template #default="{ row, $index }">
            <span>{{ row.grindToleranceUpper }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="是否签批" width="80" align="center">
        <template #default="{ row, $index }">
          <span>{{ row.isSign }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签批状态" width="80" align="center">
        <template #default="{ row, $index }">
          <span>{{ row.signStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="签批原因" width="auto" align="center">
        <template #default="{ row, $index }">
          <el-input v-model="row.signReason" :style="{ height: '25px' }" />
        </template>
      </el-table-column>
    </el-table>

    <div ref="mEndDiv" style="background-color: rgba(247, 247, 247, 0.903)">
      <el-form
        :model="formMainTable"
        class="demo-form-inline"
        :inline="true"
        :style="{
          backgroundColor: ' rgba(247, 247, 247, 0.903)',
          width: screenWidth - 96.5 + 'px',
          height: '50px',
        }"
      >
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">制单人</label>
          <el-input
            v-model="formMainTable.zdr"
            style="width: 200px; height: 35px"
            disabled
            placeholder="制单人"
            clearable
          />
        </el-form-item>
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">制单时间</label>
          <el-config-provider :locale="locale">
            <el-date-picker
              style="width: 200px"
              disabled
              v-model="formMainTable.zdsj"
              type="datetime"
              placeholder="制单时间"
            />
          </el-config-provider>
        </el-form-item>
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">修改人</label>
          <el-input
            style="width: 180px"
            v-model="formMainTable.xgr"
            disabled
            placeholder="修改人"
            clearable
          />
        </el-form-item>
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">修改时间</label>
          <el-config-provider :locale="locale">
            <el-date-picker
              style="width: 200px"
              disabled
              v-model="formMainTable.xgsj"
              type="datetime"
              placeholder="修改时间"
            />
          </el-config-provider>
        </el-form-item>
        <el-form-item class="labs" style="margin-right: 0">
          <label class="lab" style="width: 100px; padding-right: 5px">审核人</label>
          <el-input
            style="width: 200px"
            v-model="formMainTable.shr"
            disabled
            placeholder="审核人"
            clearable
          />
        </el-form-item>
        <el-form-item class="labs" style="margin-right: 0; height: 3.5vh">
          <label class="lab" style="width: 100px; padding-right: 5px">审核时间:</label>
          <el-config-provider :locale="locale">
            <el-date-picker
              style="width: 200px"
              disabled
              v-model="formMainTable.shsj"
              type="datetime"
              placeholder="审核时间"
            />
          </el-config-provider>
        </el-form-item>
      </el-form>
    </div>
  </div>

  <el-container>
    <el-header height="65px" :style="{ 'border-bottom': '1px solid #ccc' }">
      <!-- 头部按钮 -->
      <el-row type="flex" justify="end" style="background-color: rgb(211, 227, 253)">
        <div>
          <el-button @click="searchButton" type="primary"> 查询</el-button>
          <el-button @click="openInseart" type="success"> 新增</el-button>
          <el-button @click="handleSign" type="primary"> 签批</el-button>
          <el-button @click="handleDelSign" type="danger"> 弃签</el-button>
          <el-button @click="handleAudit" type="warning"> 审核</el-button>
          <el-button @click="delAudit" type="warning"> 弃审</el-button>
          <el-button @click="handleBf" type="danger">报废</el-button>
          <!-- <el-button @click="deleteButton" type="danger"> 删除</el-button> -->
        </div>
        <!-- <div class="title">需求汇总统计表</div> -->
      </el-row>
      <div
        style="
          margin-left: 6rem;
          height: 30px;

          background: rgb(241, 244, 243);
          margin-bottom: 0;
          position: relative;
          display: flex;
          justify-content: flex-start;
        "
      >
        <el-input
          style="width: 10%; height: 25px; margin-left: 2px; margin-top: 2px"
          v-model="inputName"
          placeholder="工艺名称"
        >
          <template #prefix>
            <el-icon class="">
              <search />
            </el-icon>
          </template>
        </el-input>
      </div>
    </el-header>
    <el-container>
      <el-container>
        <el-main style="padding: 2px 2px 0 2px; margin-left: 6rem">
          <el-table
            v-loading="loading"
            ref="table"
            :data="tableData"
            border
            stripe
            :cell-style="cellStyle"
            :header-cell-style="headerCellStyle"
            @selection-change="handleSelectionChange"
            @row-dblclick="handleRowClick"
            @row-click="RowClick"
            :row-style="rowState"
            :row-key="(row: any) => row.ID"
            :max-height="screenHeight"
            :height="screenHeight"
            :max-width="'300px'"
          >
            <el-table-column fixed type="index" width="60" align="center" />
            <el-table-column fixed type="selection" width="50" align="center" />
            <el-table-column
              prop="djNumber"
              label="单据编号"
              width="120"
              align="center"
            />
            <el-table-column
              prop="grindingStandardMid"
              label="磨削工艺标准编号"
              width="200"
              align="center"
            />
            <el-table-column
              prop="djStatus"
              label="单据状态"
              width="200"
              align="center"
            />
            <el-table-column
              prop="signStatus"
              label="签批状态"
              width="200"
              align="center"
            />

            <el-table-column prop="djTime" label="单据时间" width="200" align="center" />
            <el-table-column
              prop="signReason"
              label="签批原因"
              width="200"
              align="center"
            />
          </el-table>
        </el-main>
        <el-footer style="height: 20px">
          <div class="demo-pagination-block">
            <el-pagination
              v-model:current-page="page"
              v-model:page-size="limit"
              :page-sizes="[50, 500, 1000, 1500, 2000, 8000]"
              :small="true"
              :background="true"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-footer>
      </el-container>
    </el-container>
  </el-container>
  <SearchTableDialog
    ref="sed"
    @row-data="handleRowData"
    @row-datas="handleRowDatas"
  ></SearchTableDialog>
  <SearchTableDialog
    ref="sec"
    @row-data="handleRowDataAction"
    @row-datas="handleRowDataActions"
  ></SearchTableDialog>
</template>
<script setup lang="ts">
import {
  ref,
  watch,
  reactive,
  onMounted,
  onBeforeMount,
  computed,
  nextTick,
  onUnmounted,
  toRefs,
} from "vue";
import { Delete, Edit, Search, Share, Upload, Calendar } from "@element-plus/icons-vue";
import {
  ElButton,
  ElDialog,
  dialogEmits,
  ElMessage,
  ElTable,
  TableColumnCtx,
  ElMessageBox,
} from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import { CircleCloseFilled } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import axios from "../../axios/axiosInstance.ts";
import Cookies from "js-cookie";
import { format } from "date-fns";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
// crud封装组件
import * as crud from "../../components/utils/crud.ts";
import SearchTableDialog from "@/components/dialogs/SearchTableDialog.vue";
import * as notifications from "../../components/utils/notification.ts";
// 时间
// 获取当前时间
const getCurrentFormattedDateTime = () => {
  const currentDateTime = new Date();

  // 格式化当前时间
  const formattedDateTime = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  // const formattedDateTime = format(currentDateTime, "YYYY-MM-dd HH:mm:ss");

  return formattedDateTime;
};
// 获取年月日
const getCurrentFormattedDate = () => {
  const currentDateTime = new Date();

  // 格式化当前时间，只获取年月日
  const formattedDate = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });

  return formattedDate;
};
// 权限控制
const searchButtonPermissionsA = ref(false);
const menuId = ref(0);
const buttonVariables = {
  searchButtonPermissionsA,
};
const selectPermissionsButton = () => {
  const userName = Cookies.get("userName");
  axios({
    url: "/select/Permissions/Button",
    method: "post",
    data: {
      userName: userName,
      menuId: menuId.value,
    },
  }).then((res) => {
    res.data.forEach((button) => {
      const buttonName = button.buttonName;
      if (buttonVariables.hasOwnProperty(buttonName)) {
        buttonVariables[buttonName].value = true;
      }
    });
  });
};
selectPermissionsButton();
//权限结束
const tableData = ref([]);
const dialogTableVisible1 = ref(false);
const loading = ref(false);
const page = ref(1);
const limit = ref(50);
const total = ref(50);
const inputName = ref("");
const inputCode = ref("");
const selectBusinessDate = computed(() => ({
  page: page.value,
  limit: limit.value,
  inputName: inputName.value,
  //   inputCode: inputCode.value,
}));
const handleSizeChange = (val: number) => {
  selectBusinessType();
};
const handleCurrentChange = (val: number) => {
  selectBusinessType();
};
const searchButton = () => {
  selectBusinessType();
};
const selectBusinessType = async () => {
  loading.value = true;
  try {
    const res = await crud.fetchData(
      "/select/GrindingResult",
      "post",
      selectBusinessDate.value
    );
    if (res.length == 0) {
      total.value = 0;
      tableData.value = [];
      loading.value = false;
      return;
    }
    console.log(res);
    res.forEach((item) => {
      item.djStatus = item.djStatus == 0 ? "未审核" : "已审核";
      item.signStatus = item.signStatus == 0 ? "未签批" : "已签批";
    });
    tableData.value = res;
    total.value = res[0].total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
    console.error("请求失败:", error);
  }
};
selectBusinessType();
// 表格
const headerCellStyle = {
  // E9E9E7
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA", // 表头背景颜色
  fontWeight: "bold", // 表头文字粗细
  color: "#1F2129",
  // padding: "0 0 0 30px",
};
const rowState = (arg) => {
  return {
    height: "20px", // 设置合适的行高值
    fontSize: "12px", // 设置合适的字体大小值
    // color: "black",
  };
};
const handleRowClick = async (row) => {
  // isDdslDisabled.value = false;
  // isDdslDisabledYwy.value = true;
  dialogTableVisible1.value = true;
  showInsertButton.value = false;
  formMainTable.value.id = row.id;
  formMainTable.value.workOrderCode = row.workOrderNumber;
  formMainTable.value.grindingStandardMid = row.grindingStandardMid;
  formMainTable.value.djStatus = row.djStatus;
  const userName = Cookies.get("userName");
  await selectGrindingAll(row);
  //   await openGrindingProcessStandardMainId(row);
  // 回显测算类型
  // 回显子表
  axios({
    url: "/select/GrindingResultSub",
    method: "post",
    data: {
      id: row.id,
    },
  }).then((res) => {
    const testList = res.data;
    console.log(testList);

    if (testList.length === 0) {
      for (let a = 0; a < 21; a++) {
        addRow();
      }
    } else {
      const formattedData = testList.map((test, index) => ({
        uniqueCode: test.uniqueCode,
        specification: test.specification,
        material: test.material,
        model: test.model,
        grindingCapacity: test.grindingCapacity,
        roughnessStandard: test.roughnessStandard,
        totalGrindingAmount: test.totalGrindingAmount,
        residualGrindingCapacity: test.residualGrindingCapacity,
        ljgrindingTimes: test.ljgrindingTimes,
        bcGrindingCapacity: test.bcGrindingCapacity,
        bcroughnessStandard: test.bcroughnessStandard,
        isSign: test.isSign == 1 ? "是" : "否",
        signStatus: test.signStatus == 0 ? "未签批" : "已签批",
        signReason: test.signReason,
        grindStandard: test.grindStandard,
        grindToleranceUpper: test.grindToleranceUpper,
        grindToleranceLower: test.grindToleranceLower,
        roughnessToleranceUpper: test.roughnessToleranceUpper,
        roughnessToleranceLower: test.roughnessToleranceLower,
      }));
      tableData1.value = formattedData;
    }

    console.log(tableData1.value);
  });
};
const RowClick = (row, selection) => {
  table.value.toggleRowSelection(row);
};
const selectedRows = ref([]);
const table = ref();

const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (selectedRows.value.find((selectedRow) => selectedRow.ID === row.ID)) {
    return {
      backgroundColor: "#DFF0DB !important",
      borderColor: "#B9C9C7",
      padding: "4px",
    };
  } else {
    return { borderColor: "#B9C9C7", padding: "4px", margin: 0 };
  }
};
const handleSelectionChange = (selection: any) => {
  selectedRows.value = selection;
};
const screenHeight = ref(null);
const screenWidth = ref(null);
const childTableHeight = ref(null);

const getScreenHeight = () => {
  childTableHeight.value = `${window.innerHeight}` - 190 - 50;
  screenHeight.value = window.innerHeight - 146;
  screenWidth.value = window.innerWidth;
};
getScreenHeight();
const requestDataAsid = computed(() => ({
  deleteIdList: selectedRows.value,
  id: selectedRows.value.map((row) => row.id),
  workOrderCode: selectedRows.value.map((row) => row.workOrderNumber),
}));
let tableData5 = [];
const handleInput = (prop, index) => {
  const val = tableData1.value[index][prop];

  // 获取初始剩余磨削量
  const initialResidual = parseFloat(tableData5[index].residualGrindingCapacity).toFixed(
    4
  );

  // 检查是否需要重置（即输入为空或为"0"）
  if (val === "" || val === "0") {
    // 直接重置 residualGrindingCapacity 为初始值
    tableData1.value[index].residualGrindingCapacity = initialResidual;

    // 如果输入的是 bcGrindingCapacity，清空该项输入
    if (prop === "bcGrindingCapacity") {
      tableData1.value[index][prop] = "";
    }
  } else if (!isNaN(parseFloat(val)) && isFinite(val)) {
    // 对于有效数字输入，保留四位小数并计算剩余磨削量
    const bcGrinding = parseFloat(val).toFixed(4);
    tableData1.value[index][prop] = bcGrinding;

    // 计算新的剩余磨削量
    const newResidual = (parseFloat(initialResidual) - parseFloat(bcGrinding)).toFixed(4);
    tableData1.value[index].residualGrindingCapacity = newResidual;
  } else {
    // 输入非数字，清空输入字段
    tableData1.value[index][prop] = "";
  }
};
//   const val = tableData1.value[index][prop];
//   let shouldResetResidual = false; // 新增标志，用于标记是否需要重置剩余磨削量
//   if (val === "") {
//     // 用户删除了输入值
//     shouldResetResidual = true;
//     if (prop == "bcGrindingCapacity") {
//       const aDate = tableData5.value[index].residualGrindingCapacity;
//       console.log(aDate);
//     }
//   } else if (!isNaN(parseFloat(val)) && isFinite(val)) {
//     // 数字输入有效，保留四位小数
//     tableData1.value[index][prop] = parseFloat(val).toFixed(4);
//   } else {
//     // 输入非数字，不进行任何计算，直接重置输入
//     tableData1.value[index][prop] = "";
//     shouldResetResidual = true; // 同样需要重置剩余磨削量
//   }

//   if (shouldResetResidual) {
//     // 重置剩余磨削量至初始值或某个默认值
//     // 这里假设 initialResidualGrindingCapacity 存储了初始值
//     let initialResidual = parseFloat(
//       tableData1.value[index].initialResidualGrindingCapacity || 0
//     );
//     tableData1.value[index].residualGrindingCapacity = initialResidual.toFixed(4);
//   } else {
//     // 只有在输入有效时才进行剩余磨削量的计算
//     let bcGrinding = parseFloat(val);
//     let currentResidual = parseFloat(tableData1.value[index].residualGrindingCapacity);
//     tableData1.value[index].residualGrindingCapacity = (
//       currentResidual - bcGrinding
//     ).toFixed(4);
//   }

const handleInput1 = (prop, index) => {
  const val = tableData1.value[index][prop];
  if (!isNaN(parseFloat(val)) && isFinite(val)) {
    // 将数字保留四位小数
    tableData1.value[index][prop] = parseFloat(val).toFixed(4);
  } else {
    // 如果不是有效数字，清空表单
    tableData1.value[index].bcroughnessStandard = "";
  }
  let resi = parseFloat(tableData1.value[index].roughnessStandard);
  let bcroughness = parseFloat(tableData1.value[index].bcroughnessStandard);

  if (!isNaN(resi) && !isNaN(bcroughness)) {
    tableData1.value[index].roughnessStandard = (resi - bcroughness).toFixed(4); // 保持与之前逻辑一致，也保留四位小数
  } else {
    // 如果有任一值无效，可以考虑设置一个默认值或者处理逻辑
    tableData1.value[index].bcroughnessStandard = ""; // 或者设定其他默认值
  }
};
const deleteButton = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认删除", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }

      const res = await crud.sendRequest(
        "/Bdy/delete/BusinessDepartmentType/Mapping",
        "post",
        requestDataAsid.value
      );
      selectBusinessType();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const asideListData = ref([]);
const asideList = async () => {
  try {
    const res = await crud.fetchData(
      "/BusinessType/select/BusinessType/All/Auto1",
      "post",
      requestData.value
    );
    asideListData.value = res; // 将结果赋值给 ref
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const getParentIds = (nodeId) => {
  const parentIds = [];
  let currentNode = asideListData.value.find((node) => node.id === nodeId);
  while (currentNode && currentNode.parentID !== null) {
    parentIds.push(currentNode.id);
    currentNode = asideListData.value.find((node) => node.id === currentNode.parentID);
  }
  return parentIds.reverse();
};

// 新增页面展示
const openInseart = () => {
  dialogTableVisible1.value = true;
  showInsertButton.value = true;
  const userName = Cookies.get("userName");
  formMainTable.value.zdr = userName;
  const currentFormattedDate = getCurrentFormattedDate();
  formMainTable.value.zdsj = currentFormattedDate;
  nextTick(() => {
    for (let a = 0; a < 21; a++) {
      addRow();
    }
  });
};

interface RuleForm {
  id: string;
  workOrderCode: string;
  grindingProcessStandard: string;
  supplier: string;
  status: true;
  supplierAddress: string;
}
const form = reactive<RuleForm>({
  id: "",
  workOrderCode: "",
  grindingProcessStandard: "",
  supplier: "",
  supplierAddress: "",
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules<RuleForm>>({
  // name: [{ message: "请输入班组名称", trigger: "blur"  }],
});
// 子表展示
const cellStyle1 = ({ row, column, rowIndex, columnIndex }) => {
  return { borderColor: "#B9C9C7", padding: "0px", margin: 0 };
};
const showInsertButton = ref(true);
const multipleTableRef = ref();
const handleSelectionChange1 = (val: any[]) => {
  console.log("Selected Rows:", val);
};

const defaultRowData = {
  id: "",
  structureName: "",
  name: "",
  uniqueCode: "",
  specification: "",
  model: "",
  ljgrindingTimes: "",
  roughnessStandard: "",
  totalGrindingAmount: "",
  bcGrindingCapacity: "",
  bcroughnessStandard: "",
  signStatus: "",
  signReason: "",
  isSign: "",
};

const tableData1 = ref([
  {
    ...defaultRowData,
  },
  // More data...
]);
const OFFdialogTableVisible = () => {
  dialogTableVisible1.value = false;
  selectBusinessType();
  flushed();
  clearForm();
};
const clearForm = () => {
  Object.keys(form).forEach((key) => {
    if (typeof form[key] === "boolean") {
      Vue.set(form, key, true);
    } else {
      Vue.set(form, key, "");
    }
  });
};

const flushed = () => {
  organizationSelect.value = "";
  parentIDValue.value = "";
  isDisabled.value = true;
  Object.keys(form).forEach((key) => {
    form[key] = "";
  });
  tableData1.value = [];
  formMainTable.value = [];
  for (let a = 0; a < 21; a++) {
    addRow();
  }
};
const addRow = () => {
  tableData1.value.push({ ...defaultRowData });
};
const requestFormTable = computed(() => {
  const usefulDataArray = tableData1.value.filter(
    (item) => item.bcGrindingCapacity !== ""
  );
  return {
    childList: usefulDataArray,
    id: formMainTable.value.id,
    workOrderNumber: formMainTable.value.workOrderCode,
    grindingStandardMid: formMainTable.value.grindingStandardMid,
    djStatus: formMainTable.value.djStatus,
    processingWorkerId: formMainTable.value.processingWorkerId,
    processingWorkTeamId: formMainTable.value.processingWorkTeamId,
    processingShift: formMainTable.value.processingShift,
    processingDay: formMainTable.value.processingDay,
  };
});

const updateMaterialsFixed = async () => {
  try {
    if (formMainTable.value.djStatus == "已审核") {
      notifications.showMessage("已经审核的数据无法进行修改", "error");
      return;
    }
    const textinfo = ref(1);
    const flag = ref(0);
    tableData1.value.forEach((item, key) => {
      if (item["uniqueCode"] == "") {
        return;
      }
      console.log("第" + (key + 1) + "行字段名称=" + item["bcGrindingCapacity"]);
      const text = ref("");
      if (
        item["bcGrindingCapacity"] > item["residualGrindingCapacity"] &&
        item["signStatus"] == "未签批"
      ) {
        text.value = text.value == "" ? "请进行签批" : text.value + "," + "请进行签批";
      }
      flag.value = 1;
      if (text.value != "") {
        textinfo.value =
          textinfo.value == 1
            ? "第 " + (key + 1) + " 行:[" + text.value + "];" + "\n"
            : textinfo.value + "第 " + (key + 1) + " 行:[" + text.value + "];" + "\n";
      }
    });
    if (textinfo.value != 1) {
      alert(textinfo.value);
      return;
    }
    if (flag.value == 0) {
      alert("请输入数据！");
      return;
    }
    const result = await notifications.showConfirmDialog("", "请确认保存", "success");
    if (!result) {
      // 如果用户取消操作，则不执行更新操作
      return;
    }
    const res = await crud.sendRequest(
      "/update/GrindingWorkOrder",
      "post",
      requestFormTable.value
    );
    if (res.code == 200) {
      OFFdialogTableVisible();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const getAllData = async () => {
  try {
    const userName = Cookies.get("userName");
    if (formMainTable.value.djStatus == "已审核") {
      notifications.showMessage("已经审核的数据无法进行修改", "error");
      return;
    }
    if (userName !== workerName.value && userName !== "0") {
      console.log("userName是" + userName + "，workName是" + workerName.value);
      notifications.showMessage("您不属于加工班组人员或管理员，不允许进行保存", "error");
      return;
    }
    //  const textinfo = ref(1);
    //  const flag = ref(0);
    //  tableData1.value.forEach((item, key) => {
    //    if (item["uniqueCode"] == "") {
    //      return;
    //    }
    //    console.log("第" + (key + 1) + "行字段名称=" + item["bcGrindingCapacity"]);
    //    const text = ref("");
    //    if (item["bcGrindingCapacity"] == "") {
    //      text.value =
    //        text.value == "" ? "请输入本次磨削量" : text.value + "," + "请输入本次磨削量";
    //    }
    //    if (
    //      item["bcGrindingCapacity"] > item["residualGrindingCapacity"] &&
    //      item["signStatus"] == "未签批"
    //    ) {
    //      text.value = text.value == "" ? "请进行签批" : text.value + "," + "请进行签批";
    //    }
    //    flag.value = 1;
    //    if (text.value != "") {
    //      textinfo.value =
    //        textinfo.value == 1
    //          ? "第 " + (key + 1) + " 行:[" + text.value + "];" + "\n"
    //          : textinfo.value + "第 " + (key + 1) + " 行:[" + text.value + "];" + "\n";
    //    }
    //  });
    //  if (textinfo.value != 1) {
    //    alert(textinfo.value);
    //    return;
    //  }
    //  if (flag.value == 0) {
    //    alert("请输入数据！");
    //    return;
    //  }
    const result = await notifications.showConfirmDialog("", "请确认保存", "success");
    if (!result) {
      // 用户点击了取消按钮，不执行保存操作
      return;
    }
    const res = await crud.sendRequest(
      "/insert/GrindingWorkOrder",
      "post",
      requestFormTable.value
    );
    console.log(res);
    if (res.code == 200) {
      OFFdialogTableVisible();
    } else if (res.msg == "501") {
      ElMessage({
        center: true,
        showClose: true,
        grouping: true,
        offset: window.screen.height / 9,
        message: "保存失败，已经存在相同的单据",
        type: "error",
      });
      return;
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const getSelectedData = () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
};

const delAudit = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认弃审", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }
      const res = await crud.sendRequest("/del/Grinding", "post", requestDataAsid.value);
      selectBusinessType();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};

const handleAudit = async () => {
  try {
    if (formMainTable.value.djStatus == "已审核") {
      notifications.showMessage("已经审核的数据无法进行修改", "error");
      return;
    }
    const result = await notifications.showConfirmDialog("", "请确认审核", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }
      const res = await crud.sendRequest(
        "/audit/Grinding",
        "post",
        requestDataAsid.value
      );
      selectBusinessType();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const handleSign = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认签批", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }
      const res = await crud.sendRequest(
        "/sign/GrindingSign",
        "post",
        requestDataAsid.value
      );
      selectBusinessType();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const handleDelSign = async () => {
  try {
    if (formMainTable.value.djStatus == "已审核") {
      notifications.showMessage("已经审核的数据无法进行弃签", "error");
      return;
    }
    const result = await notifications.showConfirmDialog("", "请确认弃签", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }
      const res = await crud.sendRequest(
        "/del/GrindingSign",
        "post",
        requestDataAsid.value
      );
      selectBusinessType();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};
//审核
const handleBf = async () => {
  try {
    const result = await notifications.showConfirmDialog("", "请确认报废", "success");
    if (result) {
      if (selectedRows.value.length === 0) {
        notifications.showMessage("请至少选择一行进行操作", "error");
        return;
      }
      const res = await crud.sendRequest("/bf/Grinding", "post", requestDataAsid.value);
      selectBusinessType();
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const deleteSelectedRows = () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
  selectedRows.forEach((row) => {
    const index = tableData1.value.indexOf(row);
    if (index !== -1) {
      tableData1.value.splice(index, 1);
    }
  });
};
const addSign = async () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
  const result = await notifications.showConfirmDialog("", "请确认签批", "success");
  if (result) {
    if (selectedRows.value == "") {
      notifications.showMessage("请至少选择一行进行操作", "error");
      return;
    }
    selectedRows.forEach((row) => {
      // 在原始数据中找到对应行并修改singleStatus
      const index = tableData1.value.indexOf(row); // 假设每行数据有唯一的id属性，用于精确匹配
      if (index !== -1) {
        // 确保找到了对应的行
        tableData1.value[index].signStatus = "已签批";
        tableData1.value[index].signReason = "因为本次磨削量大于单次磨削量标准";
        console.log(
          "  tableData1.value[index].singleStatus的值为=" +
            tableData1.value[index].signStatus
        );
      }
    });
  }
};
const delSign = async () => {
  const selectedRows = multipleTableRef.value.getSelectionRows();
  const result = await notifications.showConfirmDialog("", "请确认弃签", "success");
  if (result) {
    if (selectedRows.value == "") {
      notifications.showMessage("请至少选择一行进行操作", "error");
      return;
    }
    selectedRows.forEach((row) => {
      // 在原始数据中找到对应行并修改singleStatus
      const index = tableData1.value.indexOf(row); // 假设每行数据有唯一的id属性，用于精确匹配
      if (index !== -1) {
        // 确保找到了对应的行
        tableData1.value[index].signStatus = "未签批";
        tableData1.value[index].signReason = "";
        console.log(
          "  tableData1.value[index].singleStatus的值为=" +
            tableData1.value[index].signStatus
        );
      }
    });
  }
};
const deleteRow = (row: any) => {
  const index = tableData1.value.indexOf(row);
  if (index !== -1) {
    tableData1.value.splice(index, 1);
  }
};
const headerCellStyle1 = {
  borderColor: "#B9C9C7",
  backgroundColor: "#F2F4FA",
  fontWeight: "500",
  color: "#1F2129",
  height: "25px",
  margin: 0,
  padding: 0,
};
// 弹窗
const indexEmployeeJob = ref(0);
const openWorkOrderCode = async () => {
  sed.value.dialogTableVisible = true;
  await openDial();
};
const openWorkOrder = async (index) => {
  indexEmployeeJob.value = index;
  console.log(indexEmployeeJob.value);
  sec.value.dialogTableVisible = true;
  await openDial2();
};
const sed = ref<any>(null);
const sec = ref<any>(null);
const tableDemo = ref([
  { type: "index", fixed: true, width: "60", align: "center" },
  { prop: "equipmentId", label: "设备编号", width: "80", align: "center" },
  { prop: "grindingStandardMid", label: "磨削标准id", width: "80", align: "center" },
  { prop: "workOrderCode", label: "工单编号", width: "80", align: "center" },
]);
const tableDemo2 = ref([
  { type: "index", fixed: true, width: "60", align: "center" },
  { prop: "id", label: "单件id", width: "80", align: "center" },
  { prop: "uniqueCode", label: "单件唯一码", width: "80", align: "center" },
  { prop: "componentId", label: "零件id", width: "80", align: "center" },
  { prop: "materialStatus", label: "物料状态", width: "80", align: "center" },
  { prop: "equipmentStructureId", label: "结构id", width: "80", align: "center" },
  { prop: "circulationState", label: "流转状态", width: "80", align: "center" },
]);
const openDial = () => {
  console.log(1);
  sed.value.ifRowChoose = false;
  sed.value.ifdynamic1 = true;
  sed.value.ifdynamic2 = false;
  sed.value.ifdynamic3 = false;
  sed.value.tableColumns = tableDemo.value;
  sed.value.apiUrl = "/select/GrindingWorkOrder";
  sed.value.searchInput();
};
const openDial2 = () => {
  console.log(2);
  sec.value.ifRowChoose = false;
  sec.value.ifdynamic1 = true;
  sec.value.ifdynamic2 = false;
  sec.value.ifdynamic3 = false;
  sec.value.tableColumns = tableDemo2.value;
  sec.value.apiUrl = "/select/ComponentSingle";
  sec.value.searchInput();
};
// const flushed1 = () => {
//   tableData1.value = [];
//   for (let a = 0; a < 21; a++) {
//     addRow();
//   }
// };
const openGrindingProcessStandardMainId = async (row) => {
  try {
    const res = await crud.fetchData("/Orc/select/GrindingProcessStandard", "post", {
      id: row.grindingStandardMid,
    });
    console.log(res[0]);
    formMainTable.value = { ...formMainTable.value, ...res[0] };
    formMainTable.value.grindingStandardName = res[0].processName;
    formMainTable.value.model = res[0].modelName;
    formMainTable.value.processProperty = res[0].processProperty.toString();
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const selectGrindingAll = async (row) => {
  try {
    const res = await crud.fetchData("/select/GrindingResult/All", "post", {
      id: row.workOrderNumber,
      page: 1,
      limit: 1,
    });
    console.log(res[0]);
    formMainTable.value = { ...formMainTable.value, ...res[0] };
    formMainTable.value.planType = res[0].planType;
    formMainTable.value.grindingStandardMid = res[0].processId;
    formMainTable.value.equipment = res[0].equipmentName;
    formMainTable.value.workOrderType = res[0].workOrderType;
    formMainTable.value.processingMethod = res[0].processingMethod;
    formMainTable.value.equipmentId = res[0].equipmentId;
    formMainTable.value.model = res[0].modelName;
    formMainTable.value.djTime = res[0].djTimes;
    formMainTable.value.grindingStandardName = res[0].processName;
    formMainTable.value.name = res[0].componentName;
    formMainTable.value.department = res[0].bmmc;
    formMainTable.value.departmentId = res[0].departmentId;
    formMainTable.value.employee = res[0].employeeName;
    formMainTable.value.employeeId = res[0].employeeId;
    formMainTable.value.measurementUnit = res[0].measurementUnit;
    formMainTable.value.processingWorkTeam = res[0].workTeam;
    formMainTable.value.processingWorker = res[0].worker;
    formMainTable.value.processingWorkTeamId = res[0].processingWorkTeamId;
    formMainTable.value.processingWorkerId = res[0].processingWorkerId;
    formMainTable.value.singlequantity = res[0].singlequantity;
    formMainTable.value.groupquantity = res[0].groupquantity;
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const selectGrindingAl = async (row) => {
  try {
    const res = await crud.fetchData("/select/GrindingResult/Al", "post", {
      id: row.workOrderCode,
      page: 1,
      limit: 1,
    });
    console.log(res[0]);
    //  formMainTable.value = { ...formMainTable.value, ...res[0] };
    formMainTable.value.planType = res[0].planType;
    formMainTable.value.grindingStandardMid = res[0].processId;
    formMainTable.value.equipment = res[0].equipmentName;
    formMainTable.value.workOrderType = res[0].workOrderType;
    formMainTable.value.processingMethod = res[0].processingMethod;
    formMainTable.value.equipmentId = res[0].equipmentId;
    formMainTable.value.model = res[0].modelName;
    formMainTable.value.djTime = res[0].djTimes;
    formMainTable.value.grindingStandardName = res[0].processName;
    formMainTable.value.name = res[0].componentName;
    formMainTable.value.department = res[0].bmmc;
    formMainTable.value.departmentId = res[0].departmentId;
    formMainTable.value.employee = res[0].worker;
    formMainTable.value.employeeId = res[0].employeeId;
    formMainTable.value.measurementUnit = res[0].measurementUnit;
    formMainTable.value.processingDay = res[0].djTimes;
    formMainTable.value.processingWorkTeam = res[0].workTeam;
    formMainTable.value.processingShift = res[0].processingShift;
    formMainTable.value.processingWorker = res[0].employeeName;
    formMainTable.value.processingWorkTeamId = res[0].processingWorkTeamId;
    formMainTable.value.processingWorkerId = res[0].processingWorkerId;
    formMainTable.value.singlequantity = res[0].singlequantity;
    formMainTable.value.groupquantity = res[0].groupquantity;
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const openWorkOrderPlanMainTable = async (row) => {
  try {
    const res = await crud.fetchData("/select/WorkOrderPlanMainTable/All", "post", {
      id: row.workOrderCode,
      page: 1,
      limit: 1,
    });
    console.log(res[0]);
    formMainTable.value = { ...formMainTable.value, ...res[0] };
    formMainTable.value.measurementUnit = res[0].measurementUnit;
    formMainTable.value.processingShift = res[0].processingShift;
    formMainTable.value.department = res[0].bmmc;
    formMainTable.value.employee = res[0].name;
    formMainTable.value.processingWorker = res[0].workName;
    formMainTable.value.processingWorkTeam = res[0].teamName;
    formMainTable.value.djTime = res[0].processingDay;
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const workerName = ref("");

const openWorker = async (row) => {
  try {
    const res = await crud.fetchData("/select/GrindingWorker", "post", {
      userId: formMainTable.value.processingWorkerId,
    });
    workerName.value = res[0].username;
    console.log(workerName.value);
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const handleRowData = async (row) => {
  formMainTable.value.workOrderCode = row.workOrderCode;
  formMainTable.value.grindingStandardMid = row.grindingStandardMid;
  const currentDateTime = new Date();
  const formattedDateTime = currentDateTime.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
  });
  formMainTable.value.djTime = formattedDateTime;
  //   await openWorkOrderPlanMainTable(row);
  //   await openGrindingProcessStandardMainId(row);
  //   await openWorker(row);
  await selectGrindingAl(row);
  axios({
    url: "/select/WorkOrderPlanSubTable",
    method: "post",
    data: {
      id: row.workOrderCode,
      page: page.value,
      limit: limit.value,
    },
  }).then((res) => {
    const testList = res.data;
    console.log(testList);
    if (testList.length > 0) {
      for (let a = 0; a < testList.length; a++) {
        tableData1.value[a].componentId = res.data[a].componentId;
        tableData1.value[a].equipmentStructureId = res.data[a].equipmentStructureId;
        tableData1.value[a].material = res.data[a].material;
        tableData1.value[a].specification = res.data[a].specification;
        tableData1.value[a].model = res.data[a].model;
        tableData1.value[a].uniqueCode = res.data[a].uniqueCode;
        tableData1.value[a].totalGrindingAmount = res.data[a].totalGrindingAmount;
        tableData1.value[a].roughnessStandard = res.data[a].roughnessStandard;
        tableData1.value[a].residualGrindingCapacity =
          res.data[a].residualGrindingCapacity;
        tableData1.value[a].ljgrindingTimes = res.data[a].ljgrindingTimes;
        tableData1.value[a].signStatus = 0;
        tableData1.value[a].isSign = 0;
        tableData1.value[a].grindStandard = res.data[a].grindStandard;
        tableData1.value[a].grindToleranceUpper = res.data[a].grindToleranceUpper;
        tableData1.value[a].grindToleranceLower = res.data[a].grindToleranceLower;
        tableData1.value[a].roughnessToleranceUpper = res.data[a].roughnessToleranceUpper;
        tableData1.value[a].roughnessToleranceLower = res.data[a].roughnessToleranceLower;
      }
      console.log(res.data);
      tableData5 = tableData1.value;
    }
  });
  sed.value.dialogTableVisible = false;
};
//  form.departmentID = row.id;
//  form.name = row.bmmc;
const handleRowDataAction = async (row) => {
  let index = indexEmployeeJob.value;
  console.log(index);
  try {
    const idDmt = ref({
      partSingleID: row.uniqueCode,
    });
    const res = await crud.fetchData("/select/CurrentDataTable", "post", idDmt.value);
    sec.value.dialogTableVisible = false;
    if (res.length > 0) {
      for (let a = 0; a < res.length; a++) {
        tableData1.value[index].uniqueCode = res[a].partSingleID;
        tableData1.value[index].specification = res[a].specification;
        tableData1.value[index].model = res[a].model;
        tableData1.value[index].material = res[a].material;
        tableData1.value[index].ljgrindingTimes = res[a].ljgrindingTimes;
        tableData1.value[index].totalGrindingAmount = res[a].totalGrindingAmount;
        tableData1.value[index].residualGrindingCapacity =
          res[a].residualGrindingCapacity;
        tableData1.value[index].roughnessStandard = res[a].roughnessStandard;
      }
    }
    //  form.departmentID = row.id;
    //  form.name = row.bmmc;
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const handleRowDataActions = (row) => {};
const handleRowDatas = (row) => {};
// 业务分类下拉
const parentIDValue = ref("");
const parentIDOptions = ref([]);
const transformResToOption = (data) => {
  const transform = (items) => {
    return items.map((item) => ({
      value: item.id,
      label: item.name,
      level: item.level,
      children: item.children ? transform(item.children) : [],
    }));
  };

  return transform(data);
};
const props = {
  checkStrictly: true,
};
const requestData = computed(() => ({}));
const selectBusinessTypeAside = async () => {
  try {
    const res = await crud.fetchData(
      "/BusinessType/select/BusinessType/Aside/Auto1",
      "post",
      requestData.value
    );

    const transformedRes = transformResToOption(res);
    parentIDOptions.value = transformedRes;
  } catch (error) {
    console.error("请求失败:", error);
  }
};
const findLevelByValue = (options, targetValue) => {
  for (const option of options) {
    // 如果当前选项的值与目标值匹配，则返回该选项的级别
    if (option.value === targetValue) {
      return option.label;
    }
    // 如果当前选项有子选项，则递归调用该函数
    if (option.children && option.children.length > 0) {
      const label = findLevelByValue(option.children, targetValue);
      // 如果在子选项中找到了目标值，则返回找到的级别
      if (label !== undefined) {
        return label;
      }
    }
  }
  // 如果未找到目标值，则返回 undefined
  return undefined;
};
// const handleChange = (value) => {
//   const selectedValue = value[value.length - 1];
//   form.businessTypeID = selectedValue;
//   const label = findLevelByValue(parentIDOptions.value, selectedValue);
//   form.businessTypeName = label;
// };

// 查询下拉框;
// 组织类型
const options = reactive([
  {
    value: "Option1",
    label: "Option1",
  },
]);

const transformResToOptions = (res) => {
  return res.map((item) => {
    return {
      value: item.code,
      label: item.codeName,
    };
  });
};

const selectSystem_parameter_sub_tableDate = reactive({
  tableName: "BusinessDepartmentTypeMappingTable",
  field: "organizationType",
});
const organizationSelect = ref("");

const selectSystem_parameter_sub_table = async () => {
  try {
    const res = await crud.fetchData(
      "/BusinessType/select/System_parameter_sub_table",
      "post",
      selectSystem_parameter_sub_tableDate
    );
    options.splice(0, options.length, ...transformResToOptions(res));
  } catch (error) {
    console.error("请求失败:", error);
  }
};
selectSystem_parameter_sub_table();
const isDisabled = ref(true);
const clickOrganizationSelect = () => {
  form.organizationType = organizationSelect.value;
  form.departmentID = "";
  form.name = "";
  isDisabled.value = false;
};

// 定义前端数据模型
const formMainTable = ref({
  id: "",
  workOrderCode: "",
  workOrderNumber: "",
  djStatus: "0",

  planType: "",
  grindingStandardMid: "",
  processingMethod: "",
  workOrderType: "",
  equipment: "",
  djStatus: "",
  djNumber: "",
  equipmentId: "",
  name: "",
  grindingStandardName: "",
  department: "",
  departmentId: "",
  employee: "",
  employeeId: "",
  processingShift: "",
  processingDay: "",
  singlequantity: "",
  groupquantity: "",
  measurementUnit: "",
  processingWorkerId: "",
  processingWorker: "",
  processingWorkTeam: "",
  processingWorkTeamId: "",
  model: "", //耗材类别名称
  // 型号
  productPurpose: "", // 产品用途ID
  productPurposeName: "", //产品用途名称
  material: "", // 材质
  materialName: "",
  zdr: "", // 材质名称
  zdsj: "",
  // 工时时长
  type: "0", // 类型
  creatorID: "", // 创建者ID
  creationTime: "", // 创建时间
  reviewer: "", // 审核者
  reviewerID: "", // 审核者ID
  reviewTime: "", // 审核时间
  modifier: "", // 修改者
  modifierID: "", // 修改者ID
  modificationTime: "", // 修改时间
});
const dynamicTitle = ref("展开参数");

const handleChange = (val: string[]) => {
  if (dynamicTitle.value == "折叠参数") {
    dynamicTitle.value = "展开参数";
    //  scollbarHeight.value = 724;
    childTableHeight.value = `${window.innerHeight}` - 252;
    collapsed.value = 48;
    return;
  }
  dynamicTitle.value = "折叠参数";
  //   affixOffset.value = 500;
  //   scollbarHeight.value = 472;
  childTableHeight.value = `${window.innerHeight}` - 513;
  collapsed.value = 300;
  return;
};
</script>
<style scoped>
.el-table {
  /* --el-table-row-hover-bg-color: rgba(0, 158, 250, 0.219) !important; */
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

/* 选中 */
.el-table {
  /* --el-table-row-hover-bg-color: #fef5f0 !important; */
  --el-table-row-hover-bg-color: rgba(254, 245, 240, 0.8) !important;
}

.down-tree ::v-deep .el-tree-node.is-expanded > .el-tree-node__children {
  display: inline;
}

.down-tree {
  height: 100%;
}

.demo-pagination-block {
  float: right;
}

.custom-dialog {
  position: fixed;
  top: 10em;
  left: 50%;
  width: 20%;
  /* 其他样式... */
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.labs {
  margin-bottom: 0px;
}

.lab {
  background-color: rgba(247, 247, 247, 0.903);
  /* border-radius: 5px; */
  text-align: center;
  margin-bottom: 0px;
  text-align: right;
}
</style>
